<?php
global $useronline;
global $visitnumber;

function getBrowser($u_agent){
   $ub = '';
   if(preg_match('/MSIE/i',$u_agent)){
      $ub = "Internet Explorer";
   }
   elseif(preg_match('/Firefox/i',$u_agent)){
      $ub = "Mozilla Firefox";
   }
   elseif(preg_match('/Chrome/i',$u_agent)){
      $ub = "Google Chrome";
   }
   elseif(preg_match('/Safari/i',$u_agent)){
      $ub = "Apple Safari";
   }
   elseif(preg_match('/Opera/i',$u_agent)){
      $ub = "Opera";
   }
   else $ub = 'Other';
   return $ub;
}





if(!isset($_SESSION['visitor'])){
   $ip = $_SERVER['REMOTE_ADDR'];
   $browser = getBrowser($_SERVER['HTTP_USER_AGENT']);
   $url = $_SERVER['REQUEST_URI'];
   $_SESSION['visitor'] = $ip;
   if(isset($_SESSION['visitor'])){
      $db = new DBQuery;
      $time = time();
      $sql = 'INSERT INTO visitor_stat(ip,browser,url,time) VALUES("'.$ip.'", "'.$browser.'", "'.$url.'", "'.$time.'")';
      $result = $db->non_query($sql);
      if($result){
         $db = new DBQuery;
         $row = $db->loadRow('SELECT counter_total FROM visitor_counter');
         $total = $row['counter_total'];
         if($total){
            $total++;
            $db->non_query('UPDATE visitor_counter SET counter_total = '.$total.', counter_update_time = '.time());
         }
         else{
            $db->non_query('INSERT visitor_counter(counter_total,counter_update_time) VALUES(1,'.time().')');
         }
      }
   }
}

//Đếm số người online


$tg=time();
$tgout=3600;
$tgnew=$tg - $tgout;
$REMOTE_ADDR = $_SERVER['REMOTE_ADDR'];
$PHP_SELF = $_SERVER['REQUEST_URI'];
$db = new DBQuery;
$sql="INSERT INTO useronline(tgtmp,ip,local) VALUES('$tg','$REMOTE_ADDR','$PHP_SELF')";
$query=$db->non_query($sql);
$sql="DELETE FROM useronline WHERE tgtmp < $tgnew";
$query=$db->non_query($sql);


//-------Đếm số người đang truy cập-----------//
$sql="SELECT DISTINCT ip FROM useronline";
$query=$db->query($sql);
$useronline = $db->num_record;


//--------Số lượt truy cập-------------//
$sql = 'SELECT counter_total FROM visitor_counter';
$visitnumber = $db->loadResult($sql);
?>